<!--登录页面-->
<template>
<div>
  <el-container>
<!--    左面-->
    <el-aside >
      <img src="../assets/loginBox.svg" alt="登录图片" class="login-img"/>
      <div>
        <h1 style="font-size: 36px">
          <strong>欢迎使用动力云客管理系统</strong>
        </h1>
      </div>
    </el-aside>
<!--    右面-->
    <el-main>
      <div class="from">
        <h2>欢迎登录</h2>
        <el-form
            ref="LoginFormRep"
            style="max-width: 600px"
            :model="loginUser"
            status-icon
            :rules="LoginForm"
            label-width="auto"
            class="demo-ruleForm"
        >
          <el-form-item label="账号" prop="loginAct">
            <el-input v-model="loginUser.loginAct" style="width: 250px" />
          </el-form-item>

          <el-form-item label="密码" prop="loginPwd">
            <el-input v-model="loginUser.loginPwd" type="password" style="width: 250px" />
          </el-form-item>

          <div class="an">
          <el-form-item>
            <el-button type="primary" @click="submitLogin(LoginFormRep)">
              登录
            </el-button>
            <el-button @click="resetForm(LoginFormRep)">重置</el-button>
          </el-form-item>
          </div>
          <el-form-item label=" ">
            <span class="ch">
            <el-checkbox v-model="loginUser.sss" name="type">记住我</el-checkbox>
            </span>
          </el-form-item>

        </el-form>
      </div>
    </el-main>
  </el-container>
</div>
</template>

<script setup>

import {onMounted, ref} from "vue";
import {doGet, doPost} from "../util/request.js";
    import {showMessage} from "../util/message.js";
    import {TOKEN_NAME} from "../util/constant.js";
import {useRouter} from "vue-router";
    //定义登录用户对象
    const loginUser = ref({})
    //验证表单规则
    const LoginForm = ref({
      loginAct: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
      ],
      loginPwd: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 10, message: '长度在 3 到 10 个字符',trigger: 'blur' },
        { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,10}$/, message: '密码由6-20位数字和字母组成', trigger: 'blur'}
      ]
    })
    // 创建提交表单验证响应式对象
    const LoginFormRep = ref({})
    //路由对象
    const router = useRouter()

    //验证表单
    const submitLogin = (formEl) => {
      if (!formEl) return
      formEl.validate((valid) => {
        if (valid) {
          // 判断是否记住我
          const  sss = loginUser.value.sss === undefined ? false : loginUser.value.sss
          const formData = new FormData()
          formData.append("loginAct",loginUser.value.loginAct)
          formData.append("loginPwd",loginUser.value.loginPwd)
          formData.append("sss",sss)
          // 将表单数据转换为查询参数
          const params = new URLSearchParams(formData)
          console.log(params.toString())

          // 发送请求
          doPost("/api/login",formData).then((resp)=>{
            console.log(resp.data.msg)
            if (resp.data.code === 200){
              //获取token
              let token = resp.data.data
              // 清除本地存储Token
              localStorage.removeItem(TOKEN_NAME)
              sessionStorage.removeItem(TOKEN_NAME)
              //判断是否记住我
              if(sss){
                //保存到本地token
                localStorage.setItem(TOKEN_NAME,token)
              }else {
                //保存到session-token
                sessionStorage.setItem(TOKEN_NAME,token)
              }
              showMessage("登录成功",'success')
                router.push("/index")
            }else {
              showMessage(resp.data.msg,'error')
            }
          })
        }
      })

    }
    // 重置表单
    const resetForm = (formEl) => {
      if (!formEl) return
      formEl.resetFields()
    }




    // 页面加载渲染后执行这个函数
    onMounted(() => {
      // 页面加载完成后，是否要自动登录
      // 从localStorage中获取令牌
      let token = localStorage.getItem(TOKEN_NAME);
      // 判断token是否有值
      if (token) {
        showMessage("登录成功",'success')
        // 有值，说明之前选择了“记住我”，可以自动登录
        // 但是需要验证token是否过期或有效
        doGet("/api/user/index",{}).then(resp => {
          if (resp.data.code === 200) {
            // 可以自动登录，页面跳转至主页面
            //router.push("/index")
            window.location.href = "/index";
          }
        })
      }
    })

</script>

<style scoped>
.ch{
  margin-left: 30%;
}
.an{
  margin-left: 30%;
}
.from{
  margin-left: 30%;
  margin-right: 30%;
  margin-top: 35%;
  text-align: center;
}
.el-main{
  text-align: center;
}
.el-aside{
    background: darkslategray;
    height: 100vh;
    width: 45%;
    text-align: center;
}
.login-img{
  width: 60%;
  margin-top: 120px;
}

</style>